package com.shine.filter;

import com.shine.constant.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * 日志追踪
 */
@Slf4j
@Component
public class TraceIdFilter extends CommonGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return GatewayConstant.FILTER_ORDER_TRACE_ID;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = UUID.randomUUID().toString().replace("-", "");
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header(GatewayConstant.TRACE_ID_HEADER, traceId)
                .build();
        exchange.getAttributes().put(GatewayConstant.TRACE_ID_HEADER, traceId);
        return chain.filter(exchange.mutate().request(request).build());
    }

}
